import React from "react";
import WebSocket from "./websocket";
import { connect } from 'react-redux';
// import store from '../../store/store';
import { chatAction, loginAction, userListAction,chatListAction} from '../../store/action/num'




class Screen extends React.Component {

  socket = null
  constructor(props) {
    super(props);
    this.state = {
      webSocketHadOpen: false,
      //重试次数
      websocketConnectedCount: 0,
    }
  }


  //连接websocket
  openWebSocket = () => {
    let head = "ws://101.43.128.205:8088";
    let url = head + "/cahtWS/" + localStorage.getItem("WsUid");

    this.socket = new WebSocket({
      socketUrl: url,
      socketMessage: (msg) => {
        let data = JSON.parse(msg.data);
        console.log("websocket接收的数据", data);

        if (data.code == 1) {
          let record = this.props.counter.chat.record;
          record.push(data)
          //处理接收消息
          this.props.dispatch(chatAction(), { record });
        }

        if (data.code == 2) {
          let userList = this.props.counter.chat.userList;

          userList = data.message;
          //处理接收消息
          this.props.dispatch({
            type: userListAction().type,
            state: { userList },
          });
        }
        if (data.code == 3) {
          let record = this.props.counter.chat.record;

          record = data.message;
          //处理接收消息
          this.props.dispatch({
            type: chatListAction().type,
            state: { record },
          });
        }


        if (data !== undefined) {
          let jsonResult = data;
          if (jsonResult.code === 401) {
            //401是后端收到心跳包，并返回的消息类型
            this.heartCheck.reset().start();    // 如果获取到消息，说明连接是正常的，重置心跳检测
          }
        }
      },
      socketClose: (msg) => {
        this.setState({
          webSocketHadOpen: false,
        })
        this.props.dispatch({
          type: loginAction().type,
          state: { login: false },
        });
      },
      socketError: () => {
        console.info("连接建立失败");
        let { websocketConnectedCount } = this.state;
        this.setState({
          webSocketHadOpen: false,
          websocketConnectedCount: websocketConnectedCount + 1,
        })
        if (this.state.websocketConnectedCount <= 5) {
          console.log('连接建立失败，尝试重连');
          this.openWebSocket();
        }
        else {
          console.log('连接建立失败，请联系管理员');
          this.props.dispatch({
            type: loginAction().type,
            state: { login: false },
          });
        }
      },
      socketOpen: () => {
        window.socket = this.socket;
        this.heartCheck.reset().start();   // 成功建立连接后，重置心跳检测
      }
    });


    //重试创建socket连接
    try {
      this.socket.connection();
    } catch (e) {
      console.log(e)
      // 捕获异常，防止js error
      this.props.dispatch({
        type: loginAction().type,
        state: { login: false },
      });
    }
    this.setState({
      webSocketHadOpen: true,
    })
  };

  //关闭websocket
  closeWebSocket = () => {

    if (this.state.webSocketHadOpen === true) {
      this.socket.closeSocket();
    }
  };

  //组件创建时
  componentDidMount () {
    //初始化心跳包对象
    this.initHeartCheck();
    //进入自动开启监控
    this.openWebSocket();

    setTimeout(()=>{
      if (window.socket) {
        this.socket.sendMessage({
          code: "2",
          type: null,
          receiverId: null,
          senderId: null,
          message: null,
          date: null,
          sendFalg: null
        })
      }
    },1500)
   
  }

  //组件销毁时
  componentWillUnmount () {
    this.closeWebSocket();
  }

  //初始化心跳包对象
  initHeartCheck = () => {
    let _this = this;
    // 心跳检测, 每隔一段时间检测连接状态，如果处于连接中，就向server端主动发送消息，来重置server端与客户端的最大连接时间，
    // 如果已经断开了，发起重连。
    this.heartCheck = {
      timeout: 10 * 1000,        //10分钟发送一次心跳包，输入毫秒数
      serverTimeoutObj: null,
      reset: function () {
        if (this.serverTimeoutObj !== undefined) {
          clearTimeout(this.serverTimeoutObj);
        }
        return this;
      },
      start: function () {
        this.serverTimeoutObj = setInterval(function () {
          if (_this.state.webSocketHadOpen) {
            if (_this.socket.readyState() === 1) {
              const message = {
                "code": 401,
                "message": "发送心跳包"
              };
              console.log("发送心跳包消息", message);
              _this.socket.sendMessage(message);
              _this.heartCheck.reset().start();    // 如果获取到消息，说明连接是正常的，重置心跳检测
            } else {
              console.log("断开状态，尝试重连");
              _this.openWebSocket();
            }
          }
        }, this.timeout)
      }
    };
  };

  render () {
    return <div></div>
  }
}

const mapStateToProps = state => ({
  counter: state
});


export default connect(mapStateToProps)(Screen);

